/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package business.service;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import crawler.common.ConfigFactory;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;

/**
 *
 * @author loctt
 */
public class TimSaoMongoDbFactory {

    private static final String MONGO_HOST = ConfigFactory.getParam("mongo_timsao", "host");
    private static final int MONGO_PORT = ConfigFactory.getIntParam("mongo_timsao", "port");
    private static final String MONGO_NAME = ConfigFactory.getParam("mongo_timsao", "dbname");
    private static final String MONGO_USER = ConfigFactory.getParam("mongo_timsao", "username");
    private static final String MONGO_PASS = ConfigFactory.getParam("mongo_timsao", "password");

    private static final Logger logger = Logger.getLogger(TimSaoMongoDbFactory.class);
    private static final Lock createLock_ = new ReentrantLock();
    private static DB db = null;
    private static MongoClient mongoClient = null;

    public static DB getConnection() {
        if (db == null) {
            createLock_.lock();
            try {
                if (db == null) {
//                    MongoCredential credential = MongoCredential.createMongoCRCredential(MONGO_USER, MONGO_NAME, MONGO_PASS.toCharArray());
                    mongoClient = new MongoClient(new ServerAddress(MONGO_HOST, MONGO_PORT)/*, Arrays.asList(credential)*/);
                    db = mongoClient.getDB(MONGO_NAME);
                }
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            } finally {
                createLock_.unlock();
            }
        }
        return db;
    }

    public static void closeConenction() {
        if (db != null) {
            try {
                mongoClient.close();
            } catch(Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    }
}
